//
//  AdsMix.m
//  PaintWar
//
//  Created by Tai Le on 10/8/14.
//
//

#import "AdsMix.h"

@implementation AdsMix

- (id)initWithType:(AdMixType)type
{
    self = [super init];
    if (self)
    {
        _type = type;
    }
    
    return self;
}

- (void)configureAds:(NSArray *) adItems
{
    _ads = adItems;
    
    _curAdRequestIndex = 0;
    
    [self startRequestForCurIndex];
}

- (void)requestNextAd
{
    [self determineNextAdIndex];
    [self startRequestForCurIndex];
}

- (void)determineNextAdIndex
{
    _curAdRequestIndex++;
    if (_curAdRequestIndex >= _ads.count)
    {
        _curAdRequestIndex = 0;
    }
}

- (void)startRequestForCurIndex
{
    if (_curAdRequestIndex >= _ads.count)
    {
        return;
    }
    
    NSLog(@"current ads index: %d", _curAdRequestIndex);
    
    AdItem *adItem = [_ads objectAtIndex:_curAdRequestIndex];
    
    if (_curAds)
    {
        [_curAds releaseAds];
    }
    
    //request ad
    _curAds = [[adItem.cls alloc] init];
    _curAds.numberOfAllowFails = adItem.numberOfAllowFails;
    _curAds.period = adItem.period;
    _curAds.adMixType = _type;
    _curAds.delegate = self;
}

- (BOOL)showAdInterstitialInViewController:(UIViewController *)controller
{
    return [_curAds showAdInterstitialInViewController:controller];
}

- (void)restartRequest
{
    _curAdRequestIndex = 0;
    
    [self startRequestForCurIndex];
}

- (void)raiseDidLoadAd:(BaseAds *)ad
{
    if ([_delegate respondsToSelector:@selector(adsMix:didLoadAd:)])
    {
        [_delegate adsMix:self didLoadAd:ad];
    }
}

- (void)raiseDidUnloadAd:(BaseAds *)ad
{
    if ([_delegate respondsToSelector:@selector(adsMix:didUnloadAdAndRestartRequest:)])
    {
        [_delegate adsMix:self didUnloadAdAndRestartRequest:ad];
    }
}

#pragma mark - Delegate
- (void)adsDidLoad:(BaseAds *)ad
{
    if ([ad isEqual:_curAds] == NO)
    {
        return;
    }
    
    NSLog(@"adsDidLoad:%@", [ad class]);
    
    [self raiseDidLoadAd:ad];
}

- (void)adsDidUnload:(BaseAds *)ad
{
    if ([ad isEqual:_curAds] == NO)
    {
        return;
    }
    
    NSLog(@"adsDidUnload:%@", [ad class]);
    
    [self raiseDidUnloadAd:ad];
    
    [self restartRequest];
}

- (void)adsDidFail:(BaseAds *)ad withError:(NSError *)error
{
    if ([ad isEqual:_curAds] == NO)
    {
        return;
    }
    
    NSLog(@"adsDidFail:%@", error);
    
    if ([ad isOutOfFail])
    {
        NSLog(@"[%@] is out of fails", [ad class]);
        [_curAds releaseAds];
        [self requestNextAd];
    }
    else
    {
        [ad performSelector:@selector(cycleAds) withObject:nil afterDelay:3];
    }
}

@end
